// 关闭加载框   this.$app.closeLoading()
import store from "@/store"
import {
	VERSION
} from '@/utils/config';
const closeLoading = () => {
	// #ifdef APP-PLUS
	plus.nativeUI.closeWaiting();
	// #endif
	// #ifndef APP-PLUS
	uni.hideLoading()
	// #endif
}
const showLoading = (title = '加载中，请稍后', modal = true) => {
	// #ifdef APP-PLUS
	plus.nativeUI.showWaiting(title, {
		background: 'rgba(0, 0, 0, .8)',
		modal: modal,
		round: 5,
		padding: '1%',
		loading: {
			display: 'block',
			height: '60px',
			icon: '/static/img/loading.png'
		},
		back: 'close'
	});
	// #endif
	// #ifndef APP-PLUS
	uni.showLoading({
		title: title,
		icon: 'none',
		mask: true
	})
	// #endif
}
const systemInfo = function() {
	/****************** 所有平台共有的系统信息 ********************/
	// 设备系统信息
	let systemInfomations = uni.getSystemInfoSync()
	// 机型适配比例系数
	let scaleFactor = 750 / systemInfomations.windowWidth
	// 当前机型-屏幕高度
	let windowHeight = systemInfomations.windowHeight * scaleFactor //rpx
	// 当前机型-屏幕宽度
	let windowWidth = systemInfomations.windowWidth * scaleFactor //rpx
	// 状态栏高度
	let statusBarHeight = (systemInfomations.statusBarHeight) * scaleFactor //rpx

	// 导航栏高度  注意：此导航栏高度只针对微信小程序有效 其他平台如自定义导航栏请使用：状态栏高度+自定义文本高度
	let navHeight = 0 //rpx
	// console.log(windowHeight,'哈哈哈哈哈');

	/****************** 微信小程序头部胶囊信息 ********************/
	// #ifdef MP
	const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
	// 胶囊高度
	let menuButtonHeight = menuButtonInfo.height * scaleFactor //rpx
	// 胶囊宽度
	let menuButtonWidth = menuButtonInfo.width * scaleFactor //rpx
	// 胶囊上边界的坐标
	let menuButtonTop = menuButtonInfo.top * scaleFactor //rpx
	// 胶囊右边界的坐标
	let menuButtonRight = menuButtonInfo.right * scaleFactor //rpx
	// 胶囊下边界的坐标
	let menuButtonBottom = menuButtonInfo.bottom * scaleFactor //rpx
	// 胶囊左边界的坐标
	let menuButtonLeft = menuButtonInfo.left * scaleFactor //rpx

	// 微信小程序中导航栏高度 = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
	navHeight = menuButtonHeight + (menuButtonTop - statusBarHeight) * 2
	// #endif


	// #ifdef MP
	return {
		scaleFactor,
		windowHeight,
		windowWidth,
		statusBarHeight,
		menuButtonHeight,
		menuButtonWidth,
		menuButtonTop,
		menuButtonRight,
		menuButtonBottom,
		menuButtonLeft,
		navHeight
	}
	// #endif

	// #ifndef MP
	return {
		scaleFactor,
		windowHeight,
		windowWidth,
		statusBarHeight
	}
	// #endif
}
// 处理多次点击
function noMultipleClicks(methods) {
	let that = this;
	if (that.noClick) {
		that.noClick = false;
		setTimeout(function() {
			that.noClick = true;
		}, 2000)
		methods();
	} else {
		console.log("请稍后点击")
	}
}

//将时间转换成IOS和安卓都能识别
const timeDiff = (str) => {
	if (str) {
		return str.replace(/\-/g, "/");
	} else {
		return ''
	}
}
const showToast = (title = '加载中...', duration = 2000, align = 'center', verticalAlign = 'bottom') => {
	setTimeout(() => {
		uni.showToast({
			title: title,
			icon: 'none'
		})
	}, 300)
}
//ajax请求
const ajax = (opts) => {
	if (!opts?.api) {
		showToast('请求格式不正确');
		return;
	}
	let that = this
	opts.api.method = opts.api.method || 'GET'
	let userInfo = uni.getStorageSync('userInfo')
	if (opts.urlParam) {
		opts.api.url += '/' + opts.urlParam
	}
	let header = {};
	let venueId = uni.getStorageSync('GYMID')
	let cookie = uni.getStorageSync('cookie')
	let shopId = uni.getStorageSync('shopId')
	header['Content-Type'] = 'application/json';
	let urlc = opts.api.url.split('do?c=')[1]
	if (opts.api.url.indexOf('do?c=3001') == -1 && opts.api.url.indexOf('do?c=3003') == -1 && opts.api.url.indexOf(
			'do?c=103026') == -1) {
		header['gymId'] = venueId;
	}
	header['userId'] = uni.getStorageSync('userId');
	header['version'] = VERSION;
	header['shopId'] = shopId;
	
	if (opts.api.url.indexOf('do?c=3001') == -1) {
		header['token'] = cookie;
	}
	header['platform'] = '3';
	// #ifdef H5
	// #endif 
	// #ifdef MP
	// if (opts.api.url.indexOf('do?c=3001') == -1) {
	// 	header['Cookie'] = cookie;
	// }
	// #endif
	const data = opts.data || {};
	let httpDefaultOpts = {
		url: opts.api.url,
		data: data,
		method: opts.api.method,
		header: header,
		dataType: "json"
	};
	// const noLoading = [
	// 	'103026',
	// 	'300002',
	// 	'300006',
	// 	'202002',
	// 	'202003',
	// 	'1033',
	// 	'500070',
	// 	'202012',
	// 	'202016',
	// 	'204004'
	// ]
	// let urlc = opts.api.url.split('do?c=')[1]
	// if (noLoading.includes(urlc)) {
	// 	console.log(1231, urlc)
	// }
	if (opts.hideLoading !== false) {
		showLoading()
	}

	return new Promise((resolve, reject) => {
		uni.request(httpDefaultOpts)
			.then((res) => {
				if (res[1]) {
					if (res[1].statusCode === 200) {
						// 判断token是否失效
						if (opts.hideLoading !== false) {
							closeLoading()
						}
						if (opts.api.url.indexOf('do?c=3001') != -1) { //判断存cookie
							if (res[1].data && res[1].data.record && res[1].data.record.token) {
								console.log('存cookie', res[1].data.record.token)
								uni.setStorageSync("cookie", res[1].data.record.token);
							}
						}
						if ((res[1]?.data?.errorCode === '00016' || res[1]?.data?.errorCode ===
								'00068') && opts.api.url.indexOf('do?c=202012') == -1) {
							showToast('登录失效，请重新登陆！')
							uni.removeStorageSync('userId');
							uni.removeStorageSync('nickName');
							uni.navigateTo({
								url: '/pages/login/login'
							})
						} else if (res[1]?.data?.errorCode === '00016' || res[1]?.data?.errorCode ===
							'00068') {
							ni.removeStorageSync('userId');
							uni.removeStorageSync('nickName');
							uni.navigateTo({
								url: '/pages/login/login'
							})
						} else {
							if (res[1]?.data?.errorCode !== '000000') {
								showToast(res[1]?.data?.errorMsg)
							}
							resolve(res[1].data);
						}
					} else {
						showToast(res[1].errorMsg);
						if (opts.hideLoading !== false) {
							closeLoading()
						}
					}
				} else {
					showToast('请求失败');
					if (opts.hideLoading !== false) {
						closeLoading()
					}
				}
				console.log('接口描述：' + opts.api.description);
				console.log('请求URL：' + opts.api.url);
				console.log('请求参数：' + opts.data ? JSON.stringify(opts.data) : '空');
				console.log('请求成功返回值：' + JSON.stringify(res));
			})
			.catch((response) => {
				reject(response);
				console.log('失败',response)
				console.log('接口描述：' + opts.api.description);
				console.log('请求URL：' + opts.api.url);
				console.log('请求参数：' + opts.data ? JSON.stringify(opts.data) : '空');
				console.log('请求失败返回值：' + JSON.stringify(response));

				if (opts.hideLoading !== false) {
					closeLoading()
				}
			});
	});
};
// 页面跳转
const jump = (url, params, tabBar = false) => {
	tabBar
		?
		uni.reLaunch({
			url: url,
		}) :
		uni.navigateTo({
			url: params ? url + params : url,
		});
};
const jump3 = (url, params, tabBar = false) => {
	uni.redirectTo({
		url: params ? url + params : url,
	})
};
const jump2 = (url, params, tabBar = false) => {
	let token = uni.getStorageSync('cookie')
	if (!token) {
		showToast('未登录，请先登录！')
		setTimeout(() => {
			jump('/pages/login/login')
		}, 1000);
		return;
	} else {
		tabBar
			?
			uni.reLaunch({
				url: url,
			}) :
			uni.navigateTo({
				url: params ? url + params : url,
			});
	}
};


// 拨打电话
const call = (tel) => {
	uni.makePhoneCall({
		phoneNumber: tel,
	});
};
const changeNumToHan = (num) => {
	var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
	var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千',
		'亿'); //可继续追加更高位转换值
	if (!num || isNaN(num)) {
		return "零";
	}
	var english = num.toString().split("");
	var result = "";
	for (var i = 0; i < english.length; i++) {
		var des_i = english.length - 1 - i; //倒序排列设值
		result = arr2[i] + result;
		var arr1_index = english[des_i];
		result = arr1[arr1_index] + result;
	}
	//将【零千、零百】换成【零】 【十零】换成【十】
	result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
	//合并中间多个零为一个零
	result = result.replace(/零+/g, '零');
	//将【零亿】换成【亿】【零万】换成【万】
	result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
	//将【亿万】换成【亿】
	result = result.replace(/亿万/g, '亿');
	//移除末尾的零
	result = result.replace(/零+$/, '');
	//将【零一十】换成【零十】
	//result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
	//将【一十】换成【十】
	result = result.replace(/^一十/g, '十');
	return result;
};

// h5页面复制文本
const h5Copy = (content) => {
	if (!document.queryCommandSupported("copy")) {
		return false;
	}
	let textarea = document.createElement("textarea");
	textarea.value = content;
	textarea.readOnly = "readOnly";
	document.body.appendChild(textarea);
	textarea.select(); // 选择对象
	textarea.setSelectionRange(0, content.length); //核心
	let result = document.execCommand("copy"); // 执行浏览器复制命令
	textarea.remove();
	showToast('复制成功！')
	return result;
};
const shifen = (shi, fen) => {
	//分割开始时间的时
	let kaiShi = shi.split(":")[0];
	//分割开始时间的分
	let kaiFen = shi.split(":")[1];
	//分割结束时间的时
	let jieShi = fen.split(":")[0];
	//分割结束时间的分
	let jieFen = fen.split(":")[1];
	//判断两者的时
	if (shi && fen) {
		if (kaiShi < jieShi) {
			console.log("大于")
		} else if (kaiShi == jieShi) {
			console.log("等于")
			if (kaiFen < jieFen) {
				console.log("等于通过")
			} else {
				showToast('结束时间要大于开始时间')
				return false;
			}
		} else {
			showToast('结束时间要大于开始时间')
			return false;
		}
	}
	return true
};

// 设置title，文字颜色，北京颜色
const setTitle = (title, titleColor, bgc) => {
	// 设置title
	uni.setNavigationBarTitle({
		title: title,
	});
	// 设置文字颜色，北京颜色
	// uni.setNavigationBarColor({
	// 	frontColor: titleColor,
	// 	backgroundColor: bgc,
	// });
};

// 验证手机号
const checkPhone = (phone) => {
	if (!/^1[23456789]\d{9}$/.test(phone)) {
		showToast("手机号格式不正确");
		return false;
	}
	return true;
};
const encryption = (phone) => {
	return phone.replace(phone.substring(3, 7), "****")
};

// 验证码邮箱
const checkEmail = (email) => {
	if (
		!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(
			email
		)
	) {
		showToast("邮箱格式不正确");
		return false;
	}
	return true;
};

// 格式化日期
const formatDate = (times) => {
	let date = new Date(times * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	let Y = date.getFullYear() + "-";
	let M =
		(date.getMonth() + 1 < 10 ?
			"0" + (date.getMonth() + 1) :
			date.getMonth() + 1) + "-";
	let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	return Y + M + D;
};

// 格式化时间0
const firstQueryTime = () => {
	let date = new Date(); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	let Y = date.getFullYear() + "-";
	let M =
		(date.getMonth() + 1 < 10 ?
			"0" + (date.getMonth() + 1) :
			date.getMonth() + 1) + "-";
	let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	let h =
		(date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
	let m =
		(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
		":";
	let s =
		date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	return Y + M + D + " " + h + m + s;
};
const formatTime = (times) => {
	let date = new Date(times * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	let Y = date.getFullYear() + "-";
	let M =
		(date.getMonth() + 1 < 10 ?
			"0" + (date.getMonth() + 1) :
			date.getMonth() + 1) + "-";
	let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	let h =
		(date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
	let m =
		(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
		":";
	let s =
		date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	return Y + M + D + " " + h + m + s;
};
// 倒计时
const djsTime = (time) => {
	let nowtime = new Date().getTime() / 1000;
	let times = time - nowtime;
	let d = parseInt(times / (60 * 60 * 24));
	let h = parseInt((times % (60 * 60 * 24)) / 3600);
	let m = parseInt(((times % (60 * 60 * 24)) % 3600) / 60);
	let s = parseInt(((times % (60 * 60 * 24)) % 3600) % 60);
	d: d < 10 ? "0" + d : d;
	h: h < 10 ? "0" + h : h;
	m: m < 10 ? "0" + m : m;
	s: s < 10 ? "0" + s : s;
	let djstime = "距结束:" + d + "天" + h + "时" + m + "分" + s + "秒";
	if (s <= 0) {
		return "已失效";
	} else {
		return djstime;
	}
};

const createTime = (tArr) => {
	for (let i = 0; i < 24; i++) {
		let timeStr = "";
		timeStr += (i < 10 ? "0" + i : i) + ":00";
		tArr.push(timeStr);
	}
	return tArr;
};

const handdleTel = (tel) => {
	let str = "" + tel;
	let str2 = tel.substr(0, 3) + "****" + tel.substr(7);
	return str2;
};
const timeago = (dateTimeStamp) => {
	var nowTime = dateTimeStamp;
	//转换为时间戳
	var thisTime = nowTime;
	thisTime = thisTime.replace(/-/g, '/');
	var time = new Date(thisTime);
	time = time.getTime();

	var minute = 1000 * 60;
	var hour = minute * 60;
	var day = hour * 24;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime();
	var diffValue = now - time;
	if (diffValue < 0) {
		return;
	}
	var monthC = diffValue / month;
	var weekC = diffValue / (7 * day);
	var dayC = diffValue / day;
	var hourC = diffValue / hour;
	var minC = diffValue / minute;
	var result = ''
	if (monthC >= 1) {
		result = "" + parseInt(monthC) + "月前";
	} else if (weekC >= 1) {
		result = "" + parseInt(weekC) + "周前";
	} else if (dayC >= 1) {
		result = "" + parseInt(dayC) + "天前";
	} else if (hourC >= 1) {
		result = "" + parseInt(hourC) + "小时前";
	} else if (minC >= 1) {
		result = "" + parseInt(minC) + "分钟前";
	} else {
		result = "刚刚";
	}
	return result
}
const ztColor = () => {
	return store.state.color
};
const baseUrl = store.state.hostName;
const baseUrls = store.state.ossUrl;
export default {
	ztColor,
	timeDiff,
	baseUrl,
	baseUrls,
	ajax, // ajax请求
	jump, // 页面跳转
	jump2,
	jump3,
	encryption,
	call, // 拨打电话
	h5Copy, // h5页面复制文本
	checkPhone, // 设置title，文字颜色，北京颜色
	checkPhone, // 验证手机号
	checkEmail, // 验证码邮箱
	formatDate, // 格式化日期
	formatTime, // 格式化时间
	shifen,
	createTime,
	firstQueryTime,
	handdleTel,
	changeNumToHan,
	djsTime,
	timeago,
	showLoading,
	closeLoading,
	systemInfo,
	setTitle,
	noMultipleClicks,
	showToast
};